package com.locatme.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.locatme.adapter.FriendViewAdapter;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.ListeAmisBD;
import com.locatme.modelBD.UtilisateurBD;
import com.main.locatme.JSONParser;
import com.main.locatme.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class FriendsFragment extends Fragment {

    private ListeAmisBD addAmis;
    private EditText txtami;
    private Utilisateur user;
    private FriendViewAdapter adapter;
    private List<String> listAmis;
    private ListeAmisBD amisBD;
    private ListView listView;
    private boolean instanceview;
    private ImageView imageViewMsg;
    private static final String TAG_SUCCESS = "success";
    private JSONParser jsonParser = new JSONParser();

    private static final String url_connect = "http://locatme.alwaysdata.net/locateme/add_friend.php";

    public FriendsFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_friends, container,
                false);
        View rootView2 = inflater.inflate(R.layout.fragment_onefriend, container, false);
        user = (Utilisateur) getActivity().getIntent().getExtras().getParcelable("user");
        txtami = (EditText) rootView.findViewById(R.id.txtfriend);
        Button btnAjout = (Button) rootView.findViewById(R.id.btnaddfriend);
        if (rootView2 != null) {
        imageViewMsg = (ImageView) rootView2.findViewById(R.id.imageViewMess);

        }
        setAmisBD(new ListeAmisBD(getActivity()));
        getAmisBD().open();


        //Rcupration de l'objet dfinissant l'utilisateur connect
        user = (Utilisateur) getActivity().getIntent().getExtras().getParcelable("user");

        listAmis = new ArrayList<String>();
        listAmis = getAmisBD().getFriendByLogin(user.getLogin());
        if(listAmis!=null){
            instanceview=true;
            adapter = new FriendViewAdapter(getActivity(),R.id.listviewfriend, listAmis);
            setListView((ListView) rootView.findViewById(R.id.listviewfriend));
            getListView().setAdapter(adapter);

            getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                    String s = (String)getListView().getItemAtPosition(position);
                    Bundle objetbunble = new Bundle();
                    objetbunble.putString("ami", s);
                        FragmentManager fragmentManager = getFragmentManager();
                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        SendMessageFragment fragment = new SendMessageFragment();
                        fragment.setArguments(objetbunble);
                        fragmentTransaction.replace(R.id.frame_container,fragment);
                        fragmentTransaction.commit();
                }
            });
        } else{
            instanceview= false;
        }
        btnAjout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ajouterAmi(v);
                if(instanceview){
                    listAmis = getAmisBD().getFriendByLogin(user.getLogin());
                    adapter = new FriendViewAdapter(getActivity(),R.id.listviewfriend, listAmis);
                    adapter.setEntries(listAmis);
                    getListView().setAdapter(adapter);
                } else {
                    Toast.makeText(getActivity(), "Refresh to see your Friend list",
                           Toast.LENGTH_LONG).show(); }
                try{
                    adapter.notifyDataSetChanged();}
                catch (Exception e){
                    Log.e("Synchro",e.toString());}
            }

        });

        return rootView;
    }



    public void ajouterAmi(View v) {

        addAmis = new ListeAmisBD(getActivity());
        addAmis.open();
        if(!addAmis.existFriend(user.getLogin(),txtami.getText().toString()))
        {
        new ajoutAmi().execute(user.getLogin(),txtami.getText().toString());
        new ajoutAmi().execute(txtami.getText().toString(),user.getLogin());
        UtilisateurBD userBD = new UtilisateurBD(getActivity());
        userBD.open();
        if (userBD.getPersonneByLogin(txtami.getText().toString()) != null) {
            addAmis.AddFriend(user.getLogin(), txtami.getText().toString());
            addAmis.AddFriend(txtami.getText().toString(),user.getLogin());
            addAmis.close();
            txtami.setText("");
            Toast.makeText(getActivity(), "New friend added",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getActivity(), "This user does not exist",
                    Toast.LENGTH_LONG).show();
        }
        }
        else
        {
            Toast.makeText(getActivity(), "Already added",
                    Toast.LENGTH_LONG).show();
        }
    }

    public ListView getListView() {
        return listView;
    }

    public void setListView(ListView listView) {
        this.listView = listView;
    }

    public ListeAmisBD getAmisBD() {
        return amisBD;
    }

    public void setAmisBD(ListeAmisBD amisBD) {
        this.amisBD = amisBD;
    }

    class ajoutAmi extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... strings) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("login",strings[0]));
            params.add(new BasicNameValuePair("favoris",strings[1]));

            JSONObject json = jsonParser.makeHttpRequest(url_connect, "POST", params);


            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                        }
                    });

                }
            } catch (JSONException e) {

                Log.d("Exeception de json : ", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

        }
    }
}
